package com.amap.search.config;

import com.baomidou.mybatisplus.MybatisConfiguration;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;


/**
 * 主数据源，需添加@Primary注解，不然会报找不到数据源错误
 */
@Configuration
@MapperScan(basePackages = "com.example.demo.mapper.db2022", sqlSessionFactoryRef = "db2022SqlSessionFactory")
public class DB2022Config {
    @Value("${spring.db2022.driver-class-name}")
    private String driverClassName;
    @Value("${spring.db2022.url}")
    private String url;
    @Value("${spring.db2022.username}")
    private String username;
    @Value("${spring.db2022.password}")
    private String password;

    private static final String MAPPER_LOCATION = "classpath:mapper/db2022/*.xml";

    /**
     * 定义数据源、账号、密码、url、连接池、连接数等
     *
     * @return
     */
    @Bean(name = "db2022Source")
    @Primary
    public DataSource db2022Source() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setJdbcUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    /**
     * 设置数据源、mapper所在位置、会话实例等
     *
     * @return
     * @throws Exception
     */
    @Bean(name = "db2022SqlSessionFactory")
    @Primary
    public SqlSessionFactory db2022SqlSessionFactory() throws Exception {
        // 创建一个对象用来插入各种数据到bean
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 设置数据源
        sqlSessionFactoryBean.setDataSource(db2022Source());
        // 设置mapper所在位置
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        // 数据库下划线，转为Java驼峰
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(configuration);
        return sqlSessionFactoryBean.getObject();
    }
    // 创建该数据源的事务管理
    @Bean(name = "oasadbTransactionManager")
    public DataSourceTransactionManager oasadbTransactionManager() throws SQLException {
        return new DataSourceTransactionManager(db2022Source());
    }

}
